#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import re
from io import BytesIO
from flask import Flask,render_template,request,redirect,session,g,abort,send_file,make_response
from functools import wraps
from flask_babel import Babel,gettext as _
from mymd import sql,qr_code
from conf import menus


app = Flask(__name__)
app.secret_key = 'JIFODJ%%^gJKHNjklnl^6732+-dutgrrIII-*/=uuddddsss'
app.config['BABEL_DEFAULT_LOCALE'] = 'zh'
babel = Babel(app)

#数据库实例化
db=sql.Mysql("127.0.0.1","root","123456","kkk",3306)

#
qr=qr_code.QR()

#检查登录
def check_login(fn):
    @wraps(fn)
    def BtnPrv(*args, **kw):
        if not session.get('s') or not session['s'].get('id'):
            return redirect('/login')
        return fn(*args, **kw)
    return BtnPrv

#检查权限-生成导航
def check_qx(fn):
    @wraps(fn)
    def BtnPrv(*args, **kw):
        name=fn.__name__
        ns=re.split('_',name)
        #print ns
        #检查权限
        if name not in session['qx']:abort(404)
        #生成导航菜单
        g.menuss, g.sub_menuss = menus.res(ns[0], name, session['qx'])
        ret = db.read('select * from role')
        print(list(ret))
        return fn(*args, **kw)
    return BtnPrv


#登录
@app.route('/login',methods=['POST','GET'])
def login():
    if request.method == 'GET':

        return render_template('login.html')

    if request.method == 'POST':
        username = request.form.get('username')
        passwd = request.form.get('passwd')
        msg = _('账号或密码错误！')
        data = {"username": username, "password": passwd}
        if username and passwd:
            sqls = '''
                select node.id,node.name
                from user
                left join user_role as urole ON user.id=1 and user.id=urole.uid
                join role ON urole.rid=role.id
                join access ON  urole.uid=access.rid
                join node  ON access.nid=node.id
            '''
            try:
                ret = db.read(sqls)
            except:
                return redirect('/login')
            #print [list(i)[0] for i in ret]
            #print [list(i)[1] for i in ret]
            session['s'] = {"id":1,"name":username}
            session['qx']=[list(i)[1] for i in ret] if ret else []
            return redirect(location='/dishes')
        else:
            return render_template('login.html')

#测试首页
@app.route('/')
@check_login
def index():
    menuss,sub_menuss=menus.res('','dishes',['dishes','dishes_cate','dishes_menus'])
    sqls='''
        select node.id,node.name
        from user
        left join user_role as urole ON user.id=1 and user.id=urole.uid
        left join role ON urole.rid=role.id
        join access ON  urole.uid=access.rid
        join node  ON access.nid=node.id
    '''
    ret=db.read(sqls)
    print [list(i)[0] for i in ret]
    print [list(i)[1] for i in ret]
    #session['s']={"client_no":123,"staff_no":110}
    return render_template('index.html',**locals())

#商品管理
@app.route('/dishes')
@check_login
@check_qx
def dishes():
    menuss, sub_menuss = g.menuss,g.sub_menuss

    return render_template('index.html', **locals())

#商品管理-分类
@app.route('/dishes/cate')
@check_login
@check_qx
def dishes_cate():
    menuss, sub_menuss = g.menuss,g.sub_menuss
    return render_template('index.html', **locals())

#登出
@app.route('/logout')
@check_login
def logout():
    session['s']={}
    session['qx']=[]
    return redirect('/login')


@app.route("/image")
def test_qrcode():
    byte_io=qr.save_bio('http://192.168.0.136:8002/index?apiKey=1&branchNo=1&tableNo=235')
    #print byte_io.getvalue()
    return send_file(byte_io, mimetype='image/png')
    # response = make_response(byte_io.getvalue())
    # response.headers['Content-Type'] = "application/octet-stream"
    # # response.headers['Content-Type'] = "application/vnd.ms-exce"
    # response.headers['Content-Disposition'] = "inline; filename=" + 'test' + '.png'
    # return response

@app.route("/image_02")
def qrcode_02():
    name='二微码123456'
    byte_io=qr.save_bio('http://192.168.0.136:8002/index?apiKey=1&branchNo=1&tableNo=235')
    #print byte_io.getvalue()
    response = make_response(byte_io.getvalue())
    response.headers['Content-Type'] = "application/octet-stream"
    # response.headers['Content-Type'] = "application/vnd.ms-exce"
    response.headers['Content-Disposition'] = "inline; filename=" + name + '.png'
    return response

if __name__=="__main__":
    app.run(host='0.0.0.0',port=5089,threaded=True,debug=True)